package com.gs.synedocket.fragment.docket;

import android.content.Intent;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.gs.synedocket.R;
import com.gs.synedocket.apiresult.ApiResultData;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.EventCode;
import com.gs.synedocket.control.TitleView;
import com.gs.synedocket.db.bean.Event;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.db.dto.ConfirmDocketDto;
import com.gs.synedocket.db.dto.DocketAddChargeDto;
import com.gs.synedocket.db.entity.DocketPhoto;
import com.gs.synedocket.db.sqlite.DBApi;
import com.gs.synedocket.dialog.DialogUtil;
import com.gs.synedocket.dialog.LoadingDialogUtils;
import com.gs.synedocket.dialog.SureDialog;
import com.gs.synedocket.dialog.ToastDialogUtils;
import com.gs.synedocket.fragment.base.BaseSignFragment;
import com.gs.synedocket.presenter.DocketAdditionalPresenter;
import com.gs.synedocket.util.DateUtil;
import com.gs.synedocket.util.DocketUtil;
import com.gs.synedocket.util.SPUtil;
import com.gs.synedocket.util.ToastUtil;
import com.gs.synedocket.view.IDocketAdditionalView;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.Date;

public class DocketAdditionalFragment extends BaseSignFragment<IDocketAdditionalView, DocketAdditionalPresenter> implements IDocketAdditionalView {

    private CheckBox cbPayCharge, cbPayDrop, cbOther;
    private TextView tvArriveSite, tvStart, tvEnd, tvDocketQty;
    private EditText etReturnQty, etRejectQty, etMileage, etSlump, etTemperature, etOther, etCbOther;
    private RadioButton rbSlump, rbTemperature, rbOvertimes, rbOther;
    private SureDialog sureDialog;
    private DocketAddChargeDto mBean;
    private RejectTextWatcher rejectTextWatcher;
    private ReturnTextWatcher returnTextWatcher;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_docket_additional;
    }

    @Override
    protected DocketAdditionalPresenter createPresenter() {
        return new DocketAdditionalPresenter();
    }

    @Override
    protected void initView() {
        TitleView viewOk = fd(R.id.view_additional);
        viewOk.setContent(fd(R.id.ll_additional_charge));
        tvDocketQty = fd(R.id.tv_docket_qty);
        etReturnQty = fd(R.id.et_accepted_qty);
        returnTextWatcher = new ReturnTextWatcher();
        etReturnQty.addTextChangedListener(returnTextWatcher);
        etRejectQty = fd(R.id.et_reject_qty);
        rejectTextWatcher = new RejectTextWatcher();
        etRejectQty.addTextChangedListener(rejectTextWatcher);
        etMileage = fd(R.id.et_mileage);
        cbPayCharge = fd(R.id.cb_pay_charge);
        cbPayDrop = fd(R.id.cb_pay_drop);
        tvStart = fd(R.id.tv_start);
        tvEnd = fd(R.id.tv_end);
        tvArriveSite = fd(R.id.tv_arrive_site);
        rbSlump = fd(R.id.rb_slump);
        etSlump = fd(R.id.et_slump);
        rbTemperature = fd(R.id.rb_temperature);
        etTemperature = fd(R.id.et_temperature);
        rbOvertimes = fd(R.id.rb_overtimes);
        rbOther = fd(R.id.rb_other);
        etOther = fd(R.id.et_other);
        cbOther = fd(R.id.cb_other);
        etCbOther = fd(R.id.et_cb_other);
        TextView tvRejectTitle = fd(R.id.tvRejectTitle);
        tvRejectTitle.setText(R.string.return_reason);
        MyRBOnCheckedChangeListener onCheckedChangeListener = new MyRBOnCheckedChangeListener();
        rbSlump.setOnCheckedChangeListener(onCheckedChangeListener);
        rbTemperature.setOnCheckedChangeListener(onCheckedChangeListener);
        rbOvertimes.setOnCheckedChangeListener(onCheckedChangeListener);
        rbOther.setOnCheckedChangeListener(onCheckedChangeListener);
        cbOther.setOnCheckedChangeListener(onCheckedChangeListener);
        MyOnClickListener onClickListener = new MyOnClickListener();
        setRadioButtonEnable(false);
        btnUnSign.setOnClickListener(onClickListener);
    }

    class RejectTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            double reject = handleSub(etReturnQty, etRejectQty, s, rejectTextWatcher);
            setRadioButtonEnable(reject > 0);
        }
    }

    class ReturnTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            double accept = handleSub(etRejectQty, etReturnQty, s, returnTextWatcher);
            cbPayCharge.setChecked(accept > 0);
        }
    }

    /**
     * “地盘有多”+“地盘退货”<=loadQty
     */
    private double handleSub(EditText anotherEt, EditText curEt, Editable s, TextWatcher textWatcher) {
        String curText = s.toString();
        if (curText.isEmpty()) {
            curText = "0";
        } else if (curText.startsWith(".")) {
            curEt.removeTextChangedListener(textWatcher);
            curText = "0" + curText;
            curEt.setText(curText);
            curEt.setSelection(curText.length());
            curEt.addTextChangedListener(textWatcher);
        }
        BigDecimal curQty = new BigDecimal(curText);
        String anotherText = anotherEt.getText().toString();
        BigDecimal anotherQty = new BigDecimal(TextUtils.isEmpty(anotherText) ? "0" : anotherText);
        if (curQty.add(anotherQty).doubleValue() > DocketUtil.getInstance().getLoadQty()) {
            curEt.setText("");
            ToastUtil.showToast(R.string.not_exceed);
            return 0;
        }
        return curQty.doubleValue();
    }

    private void setRadioButtonEnable(boolean enable) {
        rbSlump.setEnabled(enable);
        rbTemperature.setEnabled(enable);
        rbOvertimes.setEnabled(enable);
        rbOther.setEnabled(enable);
    }

    @Override
    protected void initData() {
        tvDocketQty.setText(String.valueOf(DocketUtil.getInstance().getLoadQty()));
        tvArriveSite.setText(DateUtil.DateTimeToStr(DocketUtil.getInstance().getArriveSiteAt(), "HH:mm"));
        tvStart.setText(DateUtil.DateTimeToStr(DocketUtil.getInstance().getStartDisAt(), "HH:mm"));
        tvEnd.setText(DateUtil.DateTimeToStr(new Date(), "HH:mm"));
    }

    @Override
    public Double getAcceptedQty() {
        String reject = etRejectQty.getText().toString();
        BigDecimal rejectQty = new BigDecimal(TextUtils.isEmpty(reject) ? "0" : reject);
        BigDecimal docketQty = new BigDecimal(DocketUtil.getInstance().getLoadQty() + "");
        return docketQty.subtract(rejectQty).doubleValue();
    }

    @Override
    public Double getRejectQty() {
        String s = etRejectQty.getText().toString();
        if (TextUtils.isEmpty(s)) {
            return null;
        }
        try {
            return Double.parseDouble(s);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public Double getReturnQty() {
        String s = etReturnQty.getText().toString();
        if (TextUtils.isEmpty(s)) {
            return null;
        }
        try {
            return Double.parseDouble(s);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public Boolean getPayDumpCharge() {
        return cbPayCharge.isChecked();
    }

    @Override
    public Boolean getPayMultipleDrop() {
        return cbPayDrop.isChecked();
    }

    @Override
    public Boolean getPayOther() {
        return cbOther.isChecked();
    }

    @Override
    public String getPayOtherRemark() {
        return etCbOther.getText().toString();
    }


    @Override
    public Integer getMileage() {
        String s = etMileage.getText().toString();
        if (TextUtils.isEmpty(s)) {
            return null;
        }
        try {
            return Integer.parseInt(s);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public void onUploadFileSuccess(ApiResultData<String> apiResult) {
        if (apiResult.getStatus() != 2000) {
            if (isPhoto) {
                deleteReportPhoto(listReport.size() - 1);
            }
            ToastDialogUtils.getInstance().showInfoMessage(context, apiResult.getMessage());
            hideLoading();
            return;
        }
        if (isPhoto && !listReport.isEmpty()) {
            isPhoto = false;
            listReport.set(listReport.size() - 1, new DocketPhoto(apiResult.getData()));
            hideLoading();
            return;
        }
        if (isTakePhoto) {
            isTakePhoto = false;
            mTakePhoto = apiResult.getData();
            mPresenter.uploadBase64(mSignPhoto, null);
        } else {
            confirm(apiResult.getData());
        }
    }

    @Override
    public void onUploadFileFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
        if (isPhoto) {
            deleteReportPhoto(listReport.size() - 1);
        }
    }

    @Override
    public void onUpdateSuccess(ApiResultData<String> apiResultData) {
        ToastDialogUtils.getInstance().showInfoMessage(context, apiResultData.getMessage());
        if (apiResultData.getStatus() != 2000) {
            mBean = null;
            return;
        }
        LogUtil.getInstance().insertOrReplaceData(DocketUtil.getInstance().getDocketNo() + "-添加附加費用成功");
        int driveState = DocketUtil.getInstance().getDriverState();
        Double loadQty = DocketUtil.getInstance().getLoadQty();
        double acceptedQty = mBean.getAcceptedQty() == null ? 0 : mBean.getAcceptedQty();
        double rejectQty = mBean.getRejectQty() == null ? 0 : mBean.getRejectQty();
        if (acceptedQty == 0 && rejectQty == 0) {
            driveState = 2;
        } else if (acceptedQty == loadQty) {
            driveState = 2;
        } else if (rejectQty == loadQty) {
            driveState = 4;
        } else if (rejectQty > 0 && rejectQty < loadQty) {
            driveState = 3;
        } else if (acceptedQty > 0 && acceptedQty < loadQty) {
            driveState = 3;
        }
        DBApi.getInstance().updateDocketState(mBean.getDocketId(), driveState);
        mBean.setState(0);
        DBApi.getInstance().insertNewAddCharge(mBean);
        mBean = null;
        DocketUtil.getInstance().setDriverState(driveState);
        EventBus.getDefault().post(new Event(EventCode.EVENT_DONE_COMPLETE));
    }

    private void refreshView() {
        clear();
        tvDocketQty.setText("");
        etReturnQty.setText("");
        etRejectQty.setText("");
        etSlump.setText("");
        etSlump.setEnabled(false);
        etTemperature.setText("");
        etTemperature.setEnabled(false);
        etOther.setText("");
        etOther.setEnabled(false);
        rbSlump.setChecked(false);
        rbTemperature.setChecked(false);
        rbOvertimes.setChecked(false);
        rbOther.setChecked(false);
//        tvReturnQty.setText("");
        cbPayCharge.setChecked(false);
        cbPayDrop.setChecked(false);
        etMileage.setText("");
        cbOther.setChecked(false);
    }

    @Override
    public void onUpdateFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
        mBean = null;
    }

    @Override
    public void onWithoutSignSuccess(ApiResultData<String> apiResultData) {
        ToastDialogUtils.getInstance().showInfoMessage(context, apiResultData.getMessage());
        if (apiResultData.getStatus() != 2000) {
            mBean = null;
            return;
        }
        mBean = null;
        withoutSignSuccess();
    }

    @Override
    public void onWithoutSignFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
        mBean = null;
    }

    @Override
    public void onAddInfoSuccess(ApiResultData<String> apiResult) {
        addReportSuccess(apiResult);
    }

    @Override
    public void onAddInfoFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(context);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class MyRBOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int id = buttonView.getId();
            if (id == R.id.cb_other) {
                etCbOther.setEnabled(isChecked);
                if (!isChecked) {
                    etCbOther.setText("");
                }
                return;
            }
            if (isChecked) {
                if (id == R.id.rb_slump) {
                    etSlump.setEnabled(true);
                    if (rbTemperature.isChecked()) {
                        rbTemperature.setChecked(false);
                        etTemperature.setEnabled(false);
                        etTemperature.setText("");
                    }
                    rbOvertimes.setChecked(false);
                    if (rbOther.isChecked()) {
                        rbOther.setChecked(false);
                        etOther.setEnabled(false);
                        etOther.setText("");
                    }
                } else if (id == R.id.rb_temperature) {
                    etTemperature.setEnabled(true);
                    if (rbSlump.isChecked()) {
                        rbSlump.setChecked(false);
                        etSlump.setEnabled(false);
                        etSlump.setText("");
                    }
                    rbOvertimes.setChecked(false);
                    if (rbOther.isChecked()) {
                        rbOther.setChecked(false);
                        etOther.setEnabled(false);
                        etOther.setText("");
                    }
                } else if (id == R.id.rb_overtimes) {
                    if (rbSlump.isChecked()) {
                        rbSlump.setChecked(false);
                        etSlump.setEnabled(false);
                        etSlump.setText("");
                    }
                    if (rbTemperature.isChecked()) {
                        rbTemperature.setChecked(false);
                        etTemperature.setEnabled(false);
                        etTemperature.setText("");
                    }
                    if (rbOther.isChecked()) {
                        rbOther.setChecked(false);
                        etOther.setEnabled(false);
                        etOther.setText("");
                    }
                } else if (id == R.id.rb_other) {
                    etOther.setEnabled(true);
                    if (rbSlump.isChecked()) {
                        rbSlump.setChecked(false);
                        etSlump.setEnabled(false);
                        etSlump.setText("");
                    }
                    if (rbTemperature.isChecked()) {
                        rbTemperature.setChecked(false);
                        etTemperature.setEnabled(false);
                        etTemperature.setText("");
                    }
                    rbOvertimes.setChecked(false);
                }
            }
        }
    }

    class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.btn_unsigned) {
                if (sureDialog == null) {
                    sureDialog = new SureDialog(context, R.string.unsigned, () -> {
                        ConfirmDocketDto bean = new ConfirmDocketDto();
                        bean.setDocketId(DocketUtil.getInstance().getDocketId());
                        mPresenter.comWithoutSign(bean);
                    });
                }
                sureDialog.show();
            }
        }
    }


    private void confirm(String photo) {
        mBean = new DocketAddChargeDto();
        mBean.setDocketId(DocketUtil.getInstance().getDocketId());
        mBean.setAcceptedQty(getAcceptedQty());
        mBean.setRejectQty(getRejectQty());
        if (mBean.getRejectQty() != null) {
            if (rbSlump.isChecked()) {
                mBean.setRejectReason(1);
                String s = etSlump.getText().toString();
                if (!TextUtils.isEmpty(s)) {
                    mBean.setRejectVal(Double.parseDouble(s));
                }
            } else if (rbTemperature.isChecked()) {
                mBean.setRejectReason(2);
                String s = etTemperature.getText().toString();
                if (!TextUtils.isEmpty(s)) {
                    mBean.setRejectVal(Double.parseDouble(s));
                }
            } else if (rbOvertimes.isChecked()) {
                mBean.setRejectReason(3);
            } else if (rbOther.isChecked()) {
                mBean.setRejectReason(4);
                mBean.setRejectRemark(etOther.getText().toString());
            }
        }
        mBean.setReturnQty(getReturnQty());
        mBean.setPayDumpCharge(getPayDumpCharge());
        mBean.setPayMultipleDrop(getPayMultipleDrop());
        if (getPayOther()) {
            mBean.setPayOther(getPayOther());
            mBean.setPayOtherRemark(getPayOtherRemark());
        }
        mBean.setMileage(getMileage());
        mBean.setPhoto(photo);
        mBean.setPhoto1(mTakePhoto);
        mPresenter.additionalCharge(mBean);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void confirm() {
        showLoading();
        // 判断需不需要拍照
        if (SPUtil.getInstance().getInt(AllConstants.TAKE_PHOTO,  getResources().getInteger(R.integer.take_photo)) == 1) {
            cameraUtil.takePhoto();
        }else {
            mPresenter.uploadBase64(mSignPhoto, null);
        }
    }

    @Override
    protected void submitReport() {
        mPresenter.addAccRep(createDto());
    }

    @Override
    protected void uploadReportPhoto(String url) {
        mPresenter.upload(url);
    }

    @Override
    protected void takePhoto(String url) {
        mPresenter.uploadBase64(url, true);
    }

    @Override
    protected void captureError() {
        hideLoading();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            refreshView();
        } else {
            clearReport();
            initData();
            initReport();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        photoResult(requestCode, resultCode, data);
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        photoPermissionsResult(requestCode, grantResults);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DialogUtil.getInstance().dialogDestroy(sureDialog);
    }
}
